﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RightControl.Common{
    /// <summary>
    /// 统一线程调用/日志记录  捕获处理线程内异常，防止整个应用程序crash
    /// </summary>
    public class ThreadExecutor {
        //异步线程带返回值
        public static void ExecFuncTask<T>(Func<T> func, Action<Task<T>> continueAction) {
            Task.Factory.StartNew<T>(() => {
                try {
                    return func();
                } catch (Exception ex1) {
                   LogHelper.WriteWebLog("线程异常:" + ex1.Message + "\r\n" + ex1.StackTrace);
                    return default(T);
                }
            }).ContinueWith(ret => {
                try {
                    continueAction(ret);
                } catch (Exception ex2) {
                   LogHelper.WriteWebLog("线程异常:" + ex2.Message + "\r\n" + ex2.StackTrace);
                }
            });
        }

        /// <summary>
        /// 无参数
        /// </summary>
        /// <param name="action"></param>
        /// <param name="continueAction"></param>
        public static void ExecActionTask(Action action, Action<Task> continueAction) {
            Task.Factory.StartNew(() => {
                try {
                    action();
                } catch (Exception ex1) {
                   LogHelper.WriteWebLog("线程异常:" + ex1.Message + "\r\n" + ex1.StackTrace);
                }
            }).ContinueWith(ret => {
                try {
                    continueAction(ret);
                } catch (Exception ex2) {
                   LogHelper.WriteWebLog("线程异常:" + ex2.Message + "\r\n" + ex2.StackTrace);
                }
            });
        }

        public static void ExecActionTask(Action action) {
            Task.Factory.StartNew(() => {
                try {
                    action();
                } catch (Exception ex1) {
                   LogHelper.WriteWebLog("线程异常:" + ex1.Message + "\r\n" + ex1.StackTrace);
                }
            });
        }
    }
}
